#!/bin/bash
#
# Create infra monitoring user - admin
#
# $Id: admin_add.sh 151 2011-04-08 12:46:56Z mamartynov@gmail.com $
#

[ `id -u` -ne 0 ] && { echo "only root permission. exit 1"; exit 1; }

# use: question <text> <varname_result (Y/N)>
function question() {
[ "$#" -lt 2 ] && return 1
text="$1"
flag="unknown"
while [ "$flag" != "Y" -a "$flag" != "N" ]
do
    echo -ne "\t$text [Y/N] "
    read flag
    case $flag in
    "Y"|"y")    flag="Y"
                ;;
    "N"|"n")    flag="N"
                ;;
    esac
done
[ ! -z "$2" ] && eval $2="\"$flag\""
return 0
}

echo "create user ..."
getent passwd admin > /dev/null
if [ $? -ne 0 ]; then
    /usr/sbin/useradd -m -c "Infra monitoring user" -s /bin/bash -d /home/admin -p '$1$HDv7qJgI$oBXVSh.pwFxQor8PRxoba0' admin
    [ $? -ne 0 ] && { echo "error useradd admin. exit 1"; exit 1; }
else
    echo "  warn: user admin already exist"
    question "  continue?" res
    [ "$res" = "N" ] && exit 0
fi

echo "modify /etc/sudoers ..."
cp /etc/sudoers /etc/sudoers.save
chmod +w /etc/sudoers
perl -pi -e 's/^(Defaults\s+requiretty)$/#\1/' /etc/sudoers
grep "^admin " /etc/sudoers >/dev/null || echo -e "\nadmin   ALL = (ALL) NOPASSWD: ALL\n" >> /etc/sudoers
chmod -w /etc/sudoers
diff /etc/sudoers /etc/sudoers.save && echo "  warn: change are not required"

exit 0

